// src/containers/Register/index.jsx - 更新的注册组件
import { useState } from 'react'
import { Link, useNavigate } from 'react-router-dom'
import { useAuth } from '../../contexts/AuthContext'
import './style.css'

const Register = () => {
  const navigate = useNavigate()
  const { register } = useAuth()
  
  const [formData, setFormData] = useState({
    username: '',
    email: '',
    password: '',
    confirmPassword: '',
    major: '',
    graduationYear: ''
  })
  const [showPassword, setShowPassword] = useState(false)
  const [showConfirmPassword, setShowConfirmPassword] = useState(false)
  const [loading, setLoading] = useState(false)
  const [errors, setErrors] = useState({})

  const majors = [
    '计算机科学与技术',
    '软件工程',
    '数据科学与大数据技术',
    '人工智能',
    '电子信息工程',
    '市场营销',
    '工商管理',
    '人力资源管理',
    '金融学',
    '会计学',
    '国际经济与贸易',
    '其他'
  ]

  const handleChange = (e) => {
    const { name, value } = e.target
    setFormData({
      ...formData,
      [name]: value
    })
    
    // 清除对应字段的错误信息
    if (errors[name]) {
      setErrors(prev => ({
        ...prev,
        [name]: ''
      }))
    }
    
    // 密码确认验证
    if (name === 'confirmPassword' && errors.confirmPassword) {
      if (value === formData.password) {
        setErrors(prev => ({
          ...prev,
          confirmPassword: ''
        }))
      }
    }
  }

  const validateForm = () => {
    const newErrors = {}

    // 用户名验证
    if (!formData.username.trim()) {
      newErrors.username = '请输入用户名'
    } else if (formData.username.length < 2) {
      newErrors.username = '用户名至少2个字符'
    }

    // 邮箱验证
    if (!formData.email.trim()) {
      newErrors.email = '请输入邮箱地址'
    } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) {
      newErrors.email = '请输入有效的邮箱地址'
    }

    // 专业验证
    if (!formData.major) {
      newErrors.major = '请选择专业'
    }

    // 毕业年份验证
    if (!formData.graduationYear) {
      newErrors.graduationYear = '请选择毕业年份'
    }

    // 密码验证
    if (!formData.password) {
      newErrors.password = '请输入密码'
    } else if (formData.password.length < 8) {
      newErrors.password = '密码至少8个字符'
    }

    // 确认密码验证
    if (!formData.confirmPassword) {
      newErrors.confirmPassword = '请确认密码'
    } else if (formData.password !== formData.confirmPassword) {
      newErrors.confirmPassword = '两次输入的密码不一致'
    }

    setErrors(newErrors)
    return Object.keys(newErrors).length === 0
  }

  const handleSubmit = async (e) => {
    e.preventDefault()
    
    if (!validateForm()) {
      return
    }
    
    setLoading(true)
    
    try {
      const result = await register({
        username: formData.username,
        email: formData.email,
        password: formData.password,
        major: formData.major,
        graduationYear: formData.graduationYear
      })
      
      if (result.success) {
        // 注册成功，跳转到首页
        navigate('/home', { replace: true })
      } else {
        setErrors({ submit: result.message || '注册失败' })
      }
    } catch (err) {
      setErrors({ submit: '注册过程中出现错误，请重试' })
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="auth-page">
      <div className="auth-container register-container">
        <div className="auth-header">
          <h1>加入智慧面试</h1>
          <p>创建您的账户，开启AI面试之旅</p>
        </div>
        
        <form className="auth-form" onSubmit={handleSubmit}>
          {errors.submit && (
            <div className="error-alert">
              <span className="error-icon">⚠️</span>
              <span>{errors.submit}</span>
            </div>
          )}
          
          <div className="form-row">
            <div className="form-group">
              <label htmlFor="username">用户名</label>
              <input
                type="text"
                id="username"
                name="username"
                value={formData.username}
                onChange={handleChange}
                placeholder="请输入用户名"
                className={errors.username ? 'error' : ''}
                required
              />
              {errors.username && (
                <div className="field-error">{errors.username}</div>
              )}
            </div>
            
            <div className="form-group">
              <label htmlFor="email">邮箱地址</label>
              <input
                type="email"
                id="email"
                name="email"
                value={formData.email}
                onChange={handleChange}
                placeholder="请输入邮箱"
                className={errors.email ? 'error' : ''}
                required
              />
              {errors.email && (
                <div className="field-error">{errors.email}</div>
              )}
            </div>
          </div>
          
          <div className="form-row">
            <div className="form-group">
              <label htmlFor="major">专业</label>
              <select
                id="major"
                name="major"
                value={formData.major}
                onChange={handleChange}
                className={errors.major ? 'error' : ''}
                required
              >
                <option value="">请选择专业</option>
                {majors.map(major => (
                  <option key={major} value={major}>{major}</option>
                ))}
              </select>
              {errors.major && (
                <div className="field-error">{errors.major}</div>
              )}
            </div>
            
            <div className="form-group">
              <label htmlFor="graduationYear">毕业年份</label>
              <select
                id="graduationYear"
                name="graduationYear"
                value={formData.graduationYear}
                onChange={handleChange}
                className={errors.graduationYear ? 'error' : ''}
                required
              >
                <option value="">请选择年份</option>
                {Array.from({length: 10}, (_, i) => 2024 + i).map(year => (
                  <option key={year} value={year}>{year}</option>
                ))}
              </select>
              {errors.graduationYear && (
                <div className="field-error">{errors.graduationYear}</div>
              )}
            </div>
          </div>
          
          <div className="form-group">
            <label htmlFor="password">密码</label>
            <div className="password-input">
              <input
                type={showPassword ? 'text' : 'password'}
                id="password"
                name="password"
                value={formData.password}
                onChange={handleChange}
                placeholder="请输入密码（8位以上）"
                className={errors.password ? 'error' : ''}
                minLength="8"
                required
              />
              <button
                type="button"
                className="password-toggle"
                onClick={() => setShowPassword(!showPassword)}
              >
                {showPassword ? '🙈' : '👁️'}
              </button>
            </div>
            {errors.password && (
              <div className="field-error">{errors.password}</div>
            )}
          </div>
          
          <div className="form-group">
            <label htmlFor="confirmPassword">确认密码</label>
            <div className="password-input">
              <input
                type={showConfirmPassword ? 'text' : 'password'}
                id="confirmPassword"
                name="confirmPassword"
                value={formData.confirmPassword}
                onChange={handleChange}
                placeholder="请再次输入密码"
                className={errors.confirmPassword ? 'error' : ''}
                minLength="8"
                required
              />
              <button
                type="button"
                className="password-toggle"
                onClick={() => setShowConfirmPassword(!showConfirmPassword)}
              >
                {showConfirmPassword ? '🙈' : '👁️'}
              </button>
            </div>
            {errors.confirmPassword && (
              <div className="field-error">{errors.confirmPassword}</div>
            )}
          </div>
          
          <div className="terms-check">
            <label className="checkbox-label">
              <input type="checkbox" required />
              <span>我已阅读并同意 <Link to="/terms" className="terms-link">用户协议</Link> 和 <Link to="/privacy" className="terms-link">隐私政策</Link></span>
            </label>
          </div>
          
          <button 
            type="submit" 
            className="auth-btn"
            disabled={loading}
          >
            {loading ? (
              <div className="button-loading">
                <div className="loading-spinner"></div>
                <span>注册中...</span>
              </div>
            ) : (
              '创建账户'
            )}
          </button>
        </form>
        
        <div className="auth-footer">
          <p>
            已有账户？
            <Link to="/login" className="auth-link">
              立即登录
            </Link>
          </p>
        </div>
      </div>
    </div>
  )
}

export default Register